package com.caifu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.pojo.*;
import com.caifu.service.*;
import com.caifu.util.DesUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author tww
 * ClassName: SysRoleController.java、
 * createTime: 2021年03月02日 15:17:26
 **/
@Controller
@RequestMapping("role")
public class SysRoleController extends AbstractController {
    private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysMenuService sysMenuService;

    @Resource
    private SysMenuBackService sysMenuBackService;

    @Resource
    private SysRoleMenuBackService sysRoleMenuBackService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @Resource
    private SysUserService userService;


    private String prefix = "role/";


    /**
     * 角色列表页
     */
    @GetMapping("toRolePage")
    public String toRolePage() {
        return prefix + "role";
    }


    /**
     * 角色新增页
     */
    @GetMapping("toRoleAddPage")
    public String toRoleAddPage(Model model) {
        List<SysMenu> allMenus = sysMenuService.getAllMenus();
        model.addAttribute("menus", allMenus);

        //查询板块列表（排除平台管理）
        List<Map<String, Object>> appList = sysMenuBackService.listMaps(new QueryWrapper<SysMenuBack>().select("name", "menu_no").eq("TYPE", "0").ne("menu_no", 1));
        model.addAttribute("appList", appList);
        return prefix + "role_add";
    }


    /**
     * 角色新增页
     */
    @GetMapping("toRoleUpdatePage")
    public String toRoleUpdatePage() {
        return prefix + "role_update";
    }


    /**
     * 新增修改角色
     * 2020年11月18日
     * codeBy szt
     */
    @RequestMapping("/save")
    @ResponseBody
    // @RequiresPermissions("jiaosequanxian")
    public synchronized Result save(String roleNo, String roleName, String roleDesc, String menuArr) {
        SysUser sysUser = getSysUser();
        try {

            roleNo = DesUtil.decrypt(roleNo);
            Result slt = sysRoleService.save(sysUser.getId(), roleNo, roleName, roleDesc, menuArr);
            //logService.save((SysLog) slt.getData());
            return slt;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("角色保存失败！");
            return ResultUtil.error(199, "角色保存失败！");
        }
    }


    /*
     * 功能描述: 获取权限列表
     * 192.168.1.180:9999/ATPension/sysRole/getMenuList?menuNo=19
     * @Author: szt
     * @Date:   2020/11/18
     */
    @RequestMapping("/getMenuBackList")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public JSONObject getMenuBackList(int menuNo) {
        JSONObject json = new JSONObject();
        try {
            List<Map<String, Object>> menuList = sysMenuBackService.listMaps(new QueryWrapper<SysMenuBack>().select("name", "menu_no").eq("parent_no", menuNo).orderByAsc("sort").eq("status", "1"));
            menuList.forEach(menuObj -> {
                List<Map<String, Object>> funcList = sysMenuBackService.listMaps(new QueryWrapper<SysMenuBack>().select("name", "menu_no").eq("parent_no", menuObj.get("menu_no")).eq("status", "1"));
                menuObj.put("funcList", funcList);
                menuObj.put("funcCount", funcList.size());
                funcList.forEach(funcObj -> {
                    List<Map<String, Object>> btnList = sysMenuBackService.listMaps(new QueryWrapper<SysMenuBack>().select("name", "menu_no").eq("parent_no", funcObj.get("menu_no")).eq("status", "1"));
                    funcObj.put("btnList", btnList);
                    funcObj.put("btnCount", btnList.size());
                });
            });
            json.put("code", "0");
            json.put("data", JSONArray.fromObject(menuList));
            json.put("msg", "成功");
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取角色权限列表失败！");
            json.put("code", "1");
            json.put("msg", "失败");
            return json;
        }
    }


    /**
     * 获取角色信息
     * 192.168.1.180:9999/ATPension/sysRole/getRoleInfo?roleId=D15A8E25B4249FDC
     * 2020年11月19日
     * codeBy szt
     */
    @RequestMapping("/getRoleInfo")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public Result getRoleInfo(String roleId) {
        try {
            //获取角色信息
            Map<String, Object> roleMap = sysRoleService.getMap(new QueryWrapper<SysRole>().eq("id", DesUtil.decrypt(roleId)));
            //获取服务中心角色权限
            List<SysRoleMenuBack> fuwuList = sysRoleMenuBackService.list(new QueryWrapper<SysRoleMenuBack>().eq("role_id", DesUtil.decrypt(roleId)).eq("app_menu_id", "19"));
            String fuwuCat = "";
            for (SysRoleMenuBack sysRoleMenu : fuwuList) {
                fuwuCat += sysRoleMenu.getMenuId() + "|";
            }
            //获取养老机构角色权限
            List<SysRoleMenuBack> yanglaoList = sysRoleMenuBackService.list(new QueryWrapper<SysRoleMenuBack>().eq("role_id", DesUtil.decrypt(roleId)).eq("app_menu_id", "59"));
            String yanglaoCat = "";
            for (SysRoleMenuBack sysRoleMenu : yanglaoList) {
                yanglaoCat += sysRoleMenu.getMenuId() + "|";
            }
            //获取数据看板权限
            List<SysRoleMenuBack> shujuList = sysRoleMenuBackService.list(new QueryWrapper<SysRoleMenuBack>().eq("role_id", DesUtil.decrypt(roleId)).eq("app_menu_id", "89"));
            String shujuCat = "";
            for (SysRoleMenuBack sysRoleMenu : shujuList) {
                shujuCat += sysRoleMenu.getMenuId() + "|";
            }

            //获取综合养老权限
            List<SysRoleMenuBack> zongheList = sysRoleMenuBackService.list(new QueryWrapper<SysRoleMenuBack>().eq("role_id", DesUtil.decrypt(roleId)).eq("app_menu_id", "200009"));
            String zongheCat = "";
            for (SysRoleMenuBack sysRoleMenu : zongheList) {
                zongheCat += sysRoleMenu.getMenuId() + "|";
            }
            roleMap.put("fuwuCat", fuwuCat);
            roleMap.put("yanglaoCat", yanglaoCat);
            roleMap.put("shujuCat", shujuCat);
            roleMap.put("zongheCat", zongheCat);
            roleMap.put("id", roleId);

            //获取角色授权用户数量
            int count = sysUserRoleService.getUserRoleCount(Integer.parseInt(DesUtil.decrypt(roleId)));
            roleMap.put("count", count);
            return ResultUtil.success(200, "获取角色信息成功！", roleMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取角色信息失败！");
            return ResultUtil.error(199, "获取角色信息失败！");
        }
    }


    /**
     * 删除角色
     * 2020年11月19日
     * codeBy szt
     */
    @RequestMapping("/delete")
    @ResponseBody
    // @RequiresPermissions("jiaosequanxian")
    public Result delete(String roleNo) {
        SysUser sysUser = getSysUser();
        SysRole oldRole = new SysRole();
        try {
            int count = sysUserRoleService.count(new QueryWrapper<SysUserRole>().eq("role_id", DesUtil.decrypt(roleNo)));
            if (count > 0) {
                //已授权过用户，角色不能删除
                //日志记录  sys 组织架构模块 sys-302 角色删除
                SysLog log = new SysLog(sysUser.getId(), "1", "sys", "sys-302", "9", sysUser.getLoginName() + "删除角色失败[roleId=" + oldRole.getId() + ", roleName=" + oldRole.getName() + "]！", new Date());
                //logService.save(log);
                return ResultUtil.error(199, "此角色已授权用户，不能删除！");
            } else {
                roleNo = DesUtil.decrypt(roleNo);
                oldRole = sysRoleService.getById(roleNo);
                oldRole.setState("9");
                sysRoleService.updateById(oldRole);
                //日志记录  sys 组织架构模块  sys-302 角色删除
                SysLog log = new SysLog(sysUser.getId(), "1", "sys", "sys-302", "1", sysUser.getLoginName() + "删除角色成功[roleId=" + oldRole.getId() + ", roleName=" + oldRole.getName() + "]！", new Date());
                //logService.save(log);
                return ResultUtil.success(200, "删除用户成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除角色失败！");
            //日志记录  sys 组织架构模块 sys-302 角色删除
            SysLog log = new SysLog(sysUser.getId(), "1", "sys", "sys-302", "9", sysUser.getLoginName() + "删除角色失败[roleId=" + oldRole.getId() + ", roleName=" + oldRole.getName() + "]！", new Date());
            //logService.save(log);
            return ResultUtil.error(199, "删除角色失败！");
        }
    }

    /**
     * 获取角色所属用户列表
     * 192.168.1.180:9999/ATPension/sysRole/getUserList?roleId=CE69C2C9575953DB&page=1&limit=5
     * 2020年11月19日
     * codeBy szt
     *//*
    @RequestMapping("/getUserList")
    @ResponseBody
    // @RequiresPermissions("jiaosequanxian")
    public JSONObject getUserList(int page, int limit, String roleId) {
        JSONObject json = new JSONObject();
        try {
            if (StringUtils.isNotBlank(roleId)) {
                roleId = DesUtil.decrypt(roleId);
            }
            List<Map<String, Object>> userList = new ArrayList<>();
            Page<SysUserRole> pageQuery = new Page<>(page, limit);
            IPage<Map<String, Object>> userRoleList = sysUserRoleService.pageMaps(pageQuery, new QueryWrapper<SysUserRole>().select("user_id").eq("role_id", roleId));
            for (Map<String, Object> userRole : userRoleList.getRecords()) {
                Map<String, Object> tmp = userService.getMap(new QueryWrapper<SysUser>().eq("user_no", userRole.get("user_id")));
                if (tmp != null) {
                    String tmpPhone = (String) tmp.get("PHONE");
                    tmp.put("PHONE", AesMyUtil.Decrypt(tmpPhone));
                    tmp.put("POST", Util.null2EmptyTrim((String) tmp.get("DEPT") + "/" + Util.null2EmptyTrim((String) tmp.get("POST"))));
                    Date time = (Date) tmp.get("LOGIN_TIME");
                    if (time != null) {
                        tmp.put("LOGIN_TIME", Util.dateToString(time, "yyyy-MM-dd HH:mm:ss"));
                    }
                    String status = (String) tmp.get("STATUS");
                    String statusName = ("1".equals(status) ? "开通" : "停用");
                    tmp.put("STATUS_NAME", statusName);
                    String orgName = "";
                    String orgStr = (String) tmp.get("ORG_ID");
                    if (StringUtils.isNotBlank(orgStr)) {
                        String[] orgArr = orgStr.substring(0, orgStr.length()).split(",");
                        for (String string : orgArr) {
                            SysOrganization tmpOrg = orgService.getOne(new QueryWrapper<SysOrganization>().eq("state", "1").eq("ORG_Id", string));
                            if (tmpOrg != null) {
                                orgName = orgName + tmpOrg.getOrgName() + ",";
                            }
                        }
                        if (StringUtils.isNotBlank(orgName)) {
                            orgName = orgName.substring(0, orgName.length() - 1);
                        }
                    }
                    tmp.put("ORG_NAME", orgName);
                    userList.add(tmp);
                }

            }

            json.put("code", "0");
            json.put("msg", "成功");
            json.put("count", userRoleList.getTotal());
            json.put("data", userList);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取角色列表失败！");
            json.put("code", "1");
            json.put("msg", "失败");
            return json;
        }
    }*/


    /**
     * 获取角色列表
     * 192.168.1.180:9999/ATPension/sysRole/getRoleList?page=1&limit=5
     * 2020年8月11日
     * codeBy szt
     */
    @RequestMapping("/getRoleList")
    @ResponseBody
    //@RequiresPermissions("jiaosequanxian")
    public JSONObject getRoleList(int page, int limit) {
        JSONObject json = new JSONObject();
        try {
            Page<SysRole> pageCondition = new Page<>(page, limit);
            IPage<Map<String, Object>> rolePage = sysRoleService.pageMaps(pageCondition, new QueryWrapper<SysRole>().eq("STATE", "1").orderByAsc("SORT").orderByAsc("ID"));
            for (Map<String, Object> tmp : rolePage.getRecords()) {
                Integer id = (Integer) tmp.get("id");
                tmp.put("id", DesUtil.encrypt(id + ""));
                tmp.remove("created_time");
                tmp.remove("updated_time");
                //获取用户授权数
                int count = sysUserRoleService.getUserRoleCount(id);
                tmp.put("count", count);
            }
            json.put("code", "0");
            json.put("msg", "成功");
            json.put("count", rolePage.getTotal());
            json.put("data", rolePage.getRecords());
            return json;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取角色权限列表失败！");
            json.put("code", "1");
            json.put("msg", "失败");
            return json;
        }
    }


}
